package com.sysware.p2m.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("config")
public class ConfigController {

    @NacosInjected
    ConfigService configService;

    private static Map<String, String> contentTypeMap = new HashMap<>();

    static {
        contentTypeMap.put("xml", MediaType.APPLICATION_XML_VALUE);
        contentTypeMap.put("json", MediaType.APPLICATION_JSON_VALUE);
        contentTypeMap.put("text", MediaType.TEXT_PLAIN_VALUE);
//        contentTypeMap.put("html", MediaType.TEXT_HTML_VALUE);
    }

    @RequestMapping(value = "getConfig", method = RequestMethod.GET)
    public void getConfig(@RequestParam String dataId,
                          @RequestParam(defaultValue = "DEFAULT_GROUP") String groupId,
                          HttpServletResponse response) {
        String content = null;
        try {
            content = configService.getConfig(dataId, groupId, 1000);
        } catch (NacosException e) {
            e.printStackTrace();
        }

        String extension = FilenameUtils.getExtension(dataId.toLowerCase());
        if (!contentTypeMap.containsKey(extension)) {
            extension = "text";
        }
        response.setContentType(contentTypeMap.get(extension));
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "getTest", method = RequestMethod.GET)
    public void getTest(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println(parameterMap);
        JSONObject result = new JSONObject();
        result.put("size", parameterMap.size());
        response.setContentType(contentTypeMap.get("json"));
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(result.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
